package com.dys.dao.impl;

import com.dys.dao.UserDao;
import com.dys.entity.User;
import com.dys.util.ConnectionPool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author: 疾风
 * @ClassName: UserDaoImpl
 * @Description: DAO层具体实现类
 * @CreateDate: 2024/09/26
 * @Version: v1.0.0
 */
public class UserDaoImpl implements UserDao {
    @Override
    public User selectOneUser(String username, String password) {
        // 1.获取数据库连接
        Connection conn = ConnectionPool.getConnection();
        // 2.声明需要返回的User
        User user = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 预编译SQL
            ps = conn.prepareStatement("select * from t_user where uname = ? and pwd = ?");
            // 设置预编译参数
            ps.setString(1, username);
            ps.setString(2, password);
            // 执行SQL
            rs = ps.executeQuery();
            // 处理结果集,将结果集封装为User对象
            if (rs.next()) {
                int uid = rs.getInt("uid");
                String uname = rs.getString("uname");
                String pwd = rs.getString("pwd");
                String realname = rs.getString("realname");
                int identity = rs.getInt("identity");
                // 封装对象
                user = new User(uid, uname, pwd, realname, identity);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭连接资源
            ConnectionPool.close(conn, ps, rs);
        }
        return user;
    }
}
